package com.wushi.lenovo.asia5b.app_ui.profile.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.mvp.base.BaseMvpFragment;
import com.mvp.helper.WCallBack;
import com.mvp.images.WImageLoader;
import com.mvp.refresh.AutoRefreshLayout;
import com.mvp.refresh.RefreshViewManager;
import com.mvp.ui.dialog.BottonDialog;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_config.InboxRepository;
import com.wushi.lenovo.asia5b.app_config.MemberBlanceRepository;
import com.wushi.lenovo.asia5b.app_config.OrderRepository;
import com.wushi.lenovo.asia5b.app_config.UserRepository;
import com.wushi.lenovo.asia5b.app_config.WishRepository;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.profile.mvpview.MineFragmentView;
import com.wushi.lenovo.asia5b.app_di.profile.presenter.MineFragmentPresenter;
import com.wushi.lenovo.asia5b.app_event.LoginEvent;
import com.wushi.lenovo.asia5b.app_model.credit.MemberBlanceModel;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_model.other.WebUrlType;
import com.wushi.lenovo.asia5b.app_ui.credit.activity.CreditActivity;
import com.wushi.lenovo.asia5b.app_ui.h5.CategoryActivity;
import com.wushi.lenovo.asia5b.app_ui.inbox.activity.InboxActivity;
import com.wushi.lenovo.asia5b.app_ui.other.activity.MainActivity;
import com.wushi.lenovo.asia5b.app_ui.profile.activity.PersonalInfoActivity;
import com.wushi.lenovo.asia5b.app_ui.profile.activity.ProfileActivity;
import com.wushi.lenovo.asia5b.app_ui.voucher.activity.VoucherActivity;
import com.wushi.lenovo.asia5b.app_ui.wish.activity.WishlistActivity;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import static com.luck.picture.lib.config.PictureConfig.CHOOSE_REQUEST;
import static timber.log.Timber.d;

/**
 * ================================================
 * Created by ${chenyuexueer}
 * 时间： 2018/8/18.
 * 说明：MineFragment界面
 * ================================================
 */
public class MineFragment extends BaseMvpFragment<MineFragmentView, MineFragmentPresenter>
        implements MineFragmentView {


    @BindView(R.id.civ_mine_head)
    CircleImageView civ_mine_head;
    @BindView(R.id.tv_mine_username)
    TextView tv_mine_username;
    @BindView(R.id.tv_mine_point)
    TextView tv_mine_point;
    @BindView(R.id.tv_mine_email)
    TextView tv_mine_email;
    @BindView(R.id.tv_mine_mobile)
    TextView tv_mine_mobile;
    @BindView(R.id.tv_mine_account)
    TextView tv_mine_account;
    @BindView(R.id.tv_mine_payment)
    TextView tv_mine_payment;
    @BindView(R.id.tv_mine_inbox)
    TextView tv_mine_inbox;
    @BindView(R.id.tv_mine_credit)
    TextView tv_mine_credit;
    @BindView(R.id.tv_mine_wishlist)
    TextView tv_mine_wishlist;
    @BindView(R.id.tv_mine_voucher)
    TextView tv_mine_voucher;
    @BindView(R.id.tv_mine_help)
    TextView tv_mine_help;
    @BindView(R.id.tv_mine_aboutus)
    TextView tv_mine_aboutus;
    @BindView(R.id.auto)
    AutoRefreshLayout auto;
    @BindView(R.id.tv_mine_wishcount)
    TextView tv_mine_wishcount;
    @BindView(R.id.ll_mine_vessel)
    LinearLayout ll_mine_vessel;
    @BindView(R.id.view_mine_divider)
    View view_mine_divider;


    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_mine;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        initView();
        initEvent();

    }

    @Override
    protected void lazyFetchData() {
        initData();
    }

    @Override
    protected void initView() {
        if (auto != null)
            ((RefreshViewManager) mActivity).addView(auto);
        resetView();
    }

    private void resetView() {
        setUserInfoView();
        setWishNum();
        setOrderNum();
        setInboxNum();
    }

    private void setWishNum() {
        if (tv_mine_wishcount != null) {
            if (UserRepository.isLogin()) {
                int wishCount = WishRepository.getWishCount();
                EyeUtils.setNums(tv_mine_wishcount, wishCount);
            } else {
                EyeUtils.setNums(tv_mine_wishcount, 0);
            }
        }
    }

    private void setOrderNum() {
        if (tv_mine_payment != null) {
            if (UserRepository.isLogin()) {
                int orderCount = OrderRepository.getOrderCount();
                tv_mine_payment.setVisibility(orderCount == 0 ? View.INVISIBLE : View.VISIBLE);
                tv_mine_payment.setText(orderCount + "");
            } else {
                tv_mine_payment.setVisibility(View.INVISIBLE);
            }
        }
    }

    private void setInboxNum() {
        if (tv_mine_payment != null) {
            if (UserRepository.isLogin()) {
                int inboxCount = InboxRepository.getInboxCount();
                tv_mine_inbox.setVisibility(inboxCount == 0 ? View.INVISIBLE : View.VISIBLE);
                tv_mine_inbox.setText(inboxCount + "");
            } else {
                tv_mine_inbox.setVisibility(View.INVISIBLE);
            }
        }
    }

    @Override
    protected void initData() {
        if (UserRepository.isLogin()) {
            //更新财务信息
            MemberBlanceRepository.updateMemberBalance();
            InboxRepository.updateInboxCount();
        }
    }


    @Override
    protected void initEvent() {

        if (auto != null)
            auto.setOnRefreshListener(refreshLayout -> {
                initData();
                Observable.timer(2, TimeUnit.SECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> {
                            if (auto != null)
                                auto.finishRefreshAndLoadmore();
                        });
            });
        view_mine_divider.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int bottom = view_mine_divider.getBottom();
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) ll_mine_vessel.getLayoutParams();
                layoutParams.height = bottom;
                ll_mine_vessel.setLayoutParams(layoutParams);
                view_mine_divider.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
        Disposable orderSubject = OrderRepository.getOrderCountOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(integer -> {
                    setOrderNum();
                });
        composite.add(orderSubject);
        Disposable wishSubject = WishRepository.getWishCountOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(integer -> {
                    setWishNum();
                });
        composite.add(wishSubject);
        Disposable inboxSubject = InboxRepository.getInboxCountOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(integer -> {
                    setInboxNum();
                });
        composite.add(inboxSubject);
        Disposable memberBalanceSubject = MemberBlanceRepository.getMemberBalanceOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(memberBlanceModel -> {
                    if (tv_mine_account != null) {
                        tv_mine_account.setText(memberBlanceModel == null ? "0.00" : memberBlanceModel.getBalance_value());
                    }
                });
        composite.add(memberBalanceSubject);
        Disposable userSubject = UserRepository.getUserInfoOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(userInfo -> {
                    setUserInfoView();
                });
        composite.add(userSubject);
    }

    private void setUserInfoView() {
        MemberBlanceModel memberBlanceModel = MemberBlanceRepository.getMemberBalance();
        if (UserRepository.isLogin()) {
            UserInfo userInfo = UserInfo.getUserInfo();
            //头像
            WImageLoader.displayImage(getContext(), userInfo.getAvatar_url(), civ_mine_head, R.drawable.icon_defaulthead);
            //名称
            tv_mine_username.setText(userInfo.getName());
            //积分
            tv_mine_point.setText(String.format(getString(R.string.minefragment_point), 0));
            //邮箱
            tv_mine_email.setText(userInfo.getEmail());
            //手机号
            tv_mine_mobile.setText(String.format("+%s %s", userInfo.getCalling_code(), userInfo.getMobile()));
            //账户余额
            tv_mine_account.setText(memberBlanceModel == null ? "0.00" : memberBlanceModel.getBalance_value());
        } else {
            //头像
            civ_mine_head.setImageResource(R.drawable.icon_defaulthead);
            //名称
            tv_mine_username.setText(R.string.minefragment_defaultname);
            //积分
            tv_mine_point.setText(String.format(getString(R.string.minefragment_point), 0));
            //邮箱
            tv_mine_email.setText(R.string.minefragment_defaultemail);
            //手机号
            tv_mine_mobile.setText(R.string.minefragment_defaultmobile);
            //账户余额
            tv_mine_account.setText("0.00");
        }

    }

    @OnClick({
            R.id.tv_mine_credit,
            R.id.tv_mine_wishlist,
            R.id.tv_mine_voucher,
            R.id.tv_mine_help,
            R.id.tv_mine_aboutus,
            R.id.rl_mine_account,
            R.id.rl_mine_payment,
            R.id.rl_mine_index,
            R.id.rl_mine_profile,
            R.id.ll_mine_wishlist,
            R.id.tv_mine_username,
            R.id.civ_mine_head
    })
    @Override
    public void onClick(View v) {
        if (!UserRepository.isLogin(getContext())) {
            return;
        }
        switch (v.getId()) {
            case R.id.civ_mine_head: {
                BottonDialog bottonDialog = new BottonDialog(getContext());
                bottonDialog.show();
                bottonDialog.setCallBack(new WCallBack<Integer>() {
                    @Override
                    public void callback(Integer integer) {
                        if (integer == null) {
                            return;
                        }
                        switch (integer) {
                            case 0://拍照
                                EyeUtils.tagPermission();
                                new RxPermissions(getActivity())
                                        .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        .subscribe(aBoolean -> {
                                            if (aBoolean) {
                                                // 单独拍照
                                                PictureSelector.create(MineFragment.this)
                                                        .openCamera(PictureMimeType.ofImage())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                                                        .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles
                                                        .maxSelectNum(1)// 最大图片选择数量
                                                        .minSelectNum(1)// 最小选择数量
                                                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                                                        .previewImage(true)// 是否可预览图片
                                                        .enablePreviewAudio(false) // 是否可播放音频
                                                        .isCamera(true)// 是否显示拍照按钮
                                                        .enableCrop(false)// 是否裁剪
                                                        .compress(true)// 是否压缩
                                                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                                                        .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                                                        .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                                                        .openClickSound(true)// 是否开启点击声音
                                                        .previewEggs(false)//预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                                        //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                                        //.cropCompressQuality(90)// 裁剪压缩质量 默认为100
                                                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                                                        //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                                                        //.rotateEnabled() // 裁剪是否可旋转图片
                                                        //.scaleEnabled()// 裁剪是否可放大缩小图片
                                                        //.videoQuality()// 视频录制质量 0 or 1
                                                        //.videoSecond()////显示多少秒以内的视频or音频也可适用
                                                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code

                                            } else {
                                                ToastUtil.showToast(getString(R.string.permission_error1));
                                            }
                                        });
                                // 进入相册 以下是例子：不需要的api可以不写
//                                PictureSelector.create(getActivity())
//                                        .openCamera(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()
//                                        .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles
//                                        .previewImage(true)// 是否可预览图片
//                                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
//                                        .compress(true)// 是否压缩
//                                        .openClickSound(false)// 是否开启点击声音
//                                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code


                                break;
                            case 1://打开相册
                                EyeUtils.tagPermission();
                                new RxPermissions(getActivity())
                                        .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        .subscribe(aBoolean -> {
                                            if (aBoolean) {
                                                PictureSelector.create(MineFragment.this)
                                                        .openGallery(PictureMimeType.ofImage())
                                                        .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles
                                                        .previewImage(true)// 是否可预览图片
                                                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                                                        .compress(true)// 是否压缩
                                                        .openClickSound(false)// 是否开启点击声音
                                                        .maxSelectNum(1)
                                                        .forResult(CHOOSE_REQUEST);//结果回调onActivityResult code
                                            } else {
                                                ToastUtil.showToast(getString(R.string.permission_error1));
                                            }
                                        });

                                break;
                        }
                    }
                });
            }
            break;
            case R.id.rl_mine_account:
            case R.id.tv_mine_credit:
                startActivity(new Intent(getContext(), CreditActivity.class));
                break;
            case R.id.ll_mine_wishlist:
            case R.id.tv_mine_wishlist:
//                ((MainActivity) getActivity()).setTabCurrenItem(1);
                startActivity(new Intent(getContext(), WishlistActivity.class));
                break;
            case R.id.tv_mine_voucher:
                startActivity(new Intent(getContext(), VoucherActivity.class));
                break;
            case R.id.tv_mine_help: {
                CategoryActivity.startCategoryActivity(getContext(), WebUrlType.helpcenter);
            }
            break;
            case R.id.tv_mine_aboutus: {
                CategoryActivity.startCategoryActivity(getContext(), WebUrlType.aboutus);
            }
            break;
            case R.id.rl_mine_payment:
                MainActivity mainActivity = (MainActivity) getActivity();
                mainActivity.setTabCurrenItem(3);
                break;
            case R.id.rl_mine_index:
//                ToastUtil.showToast("index");
                startActivity(new Intent(getContext(), InboxActivity.class));
                break;
            case R.id.rl_mine_profile:
                startActivity(new Intent(getContext(), ProfileActivity.class));
                break;
            case R.id.tv_mine_username:
                startActivity(new Intent(getContext(), PersonalInfoActivity.class));
                break;
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onLoginEvent(LoginEvent event) {
        if (event != null) {

            if (TextUtils.equals(event.loginState, CommonConstant.LOGIN_SUCCESS)) {
                d("--->>>>>>>>---登录成功");
                resetView();
            } else if (TextUtils.equals(event.loginState, CommonConstant.LOGOUT_SUCCESS)) {
                d("--->>>>>>>>---登出成功");
                hasFetchData = false;
                resetView();
            }

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void dismissLoadingBar(Object dississTag) {
        super.dismissLoadingBar(dississTag);
        if (auto != null) {
            auto.finishRefreshAndLoadmore();
        }
    }

    @Override
    public void showLoadingFailureError(Throwable throwable) {
        super.showLoadingFailureError(throwable);
        if (auto != null) {
            auto.finishRefreshAndLoadmore();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK)
            return;

        switch (requestCode) {

            case PictureConfig.CHOOSE_REQUEST: {
                // 图片选择
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                if (selectList != null && selectList.size() > 0) {
                    LocalMedia localMedia = selectList.get(0);
                    String path = localMedia.getCompressPath();
                    if (!TextUtils.isEmpty(path)) {
                        Glide.with(mContext)
                                .load(path)
                                .into(civ_mine_head);
                        getPresenter().updateMemberHead(path);
                    }


                }
                break;
            }
        }
    }
}
